<script setup>
import _ from 'lodash';
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import OrderRobot from './order-robot.vue'
import { DFT_ICONS } from '@jzl/icons';
import { api } from '@jzl/api';

// 定义props
const props = defineProps({
  form: {
    type: Object,
    default: null
  },
  direction: {
    type: String,
    default: 'rtl'
  },
  type: {
    type: [Number, String],
    default: 3
  },
  node: {
    type: Object,
    default: null
  }
})

// 定义emits
const emit = defineEmits(['change'])

// 响应式数据
const tasks = ref([])
const currentInfo = ref({})
const targetForm = ref({})
const propShow = ref(false)
const submiting = ref(false)
const saveMode = ref('save')
const currentNodeTitle = ref('')

// 计算属性
const isFlowForm = computed(() => {
  return props.form && props.form.use_type === 'WORKFLOW'
})

// 过滤器转换为方法
const actionTypeLabel = (type) => {
  if (type === 'INSERT') {
    return "新增数据"
  } else if (type === 'UPDATE') {
    return "修改已有数据"
  } else if (type === 'DELETE') {
    return "删除已有数据"
  } else if (type === 'SCRIPT') {
    return "低码开发"
  }
  return ""
}

const init = async () => {
  let mode = 'save'
  let taskList = await api.order.getOrderSynctasks()

  submiting.value = false
  tasks.value = taskList || []
  saveMode.value = mode
}

const handleShowProp = (info) => {
  propShow.value = true

  if (info) {
    currentInfo.value = info
    currentNodeTitle.value = `修改数据同步/低码`
  } else {
    currentInfo.value = {}
    currentNodeTitle.value = `新增数据同步/低码`
  }
}

const handlePropClose = () => {
  propShow.value = false
}

const handleShowFormSelectWin = async () => {
  this.$WinForms({
    type: 'form',
    onSelect: async (info) => {
      let form = _.get(info, 'form')
      if (!form || !form.form_code) return

      let formId = _.get(form, 'form_id')
      let formInfo = await this.$japi.form.getFormById(formId)
      targetForm.value = formInfo
      currentInfo.value.target_form_id = _.get(formInfo, 'form_id')
    }
  })
}

const handleChangeStatus = async (task) => {
  if (!task || !task.st_code) {
    return
  }

  if (saveMode.value === 'temp') {
    return
  }

  if (task.status === 1) {
    let ret = await this.$japi.order.enableSynctask(task.st_id)

    if (!ret) {
      task.status = 2
    }
  } else if (task.status === 2) {
    let ret = await this.$japi.order.disableSynctask(task.st_id)

    if (!ret) {
      task.status = 1
    }
  }
}

const handleShowExeLog = () => {
  this.$message('开发中，敬请期待。')
}

const _remove = async (task) => {
  let id = _.get(task, 'st_id')
  let st_code = _.get(task, 'st_code')

  if (saveMode.value === 'temp' || !id) {
    let idx = _.findIndex(tasks.value, { st_code })
    tasks.value.splice(idx, 1)
  } else {
    let ret = await this.$japi.order.removeSynctask(id)
    if (ret) {
      init()
    }
  }
}

const handleRemove = (task, idx) => {
  if (!task || !task.st_code) {
    return
  }
  this.$confirm(`规则删除将不可恢复, 是否继续?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    _remove(task, idx)
  }).catch(() => {})
}

const cancel = () => {
  propShow.value = false
}

const handleClose = () => {
  propShow.value = false
}

const handleSave = (task) => {
  propShow.value = false

  let st_code = _.get(task, 'st_code')

  if (!st_code) return

  let idx = _.findIndex(tasks.value, { st_code })

  if (idx >= 0) {
    let orig = tasks.value[idx]
    _.assign(orig, task)
  } else {
    tasks.value.push(task)
  }
}

// 生命周期
onMounted(() => {
  currentInfo.value.form_id = _.get(props.form, 'form_id')
  init()
})

// 监听器
watch(() => [ props.form?.form_id, props.node?.node_code ], () => {
  init()
})

watch(tasks, (val) => {
  emit('change', val)
}, { deep: true })
</script>

<template>
  <div class="sync-tasks">
    <el-button
      type="primary"
      style="margin-bottom: 10px;"
      @click="handleShowProp()"
    >
      <template #icon>
        <JIcon :icon="DFT_ICONS.add" />
      </template>订单支付后，数据同步/低码</el-button>
    <span class="tip-txt">若添加多个规则，将按照顺序依次执行</span>

    <div v-for="(t, idx) in tasks" @click="handleShowProp(t)"
         class="sync-task" :class="{ 'active': currentInfo && t.st_code === currentInfo.st_code }" :key="t.st_code">
      <div class="seq" v-text="t.order || (1 + idx)"></div>
      <div class="info">
        <ul>
          <li v-if="t.form">触发表单：<b>{{ t.form.form_name }}</b></li>
          <li>执行动作：<b>{{ actionTypeLabel(t.action_type) }}</b></li>
          <li v-if="t.targetForm">目标表单：<b>{{ t.targetForm.form_name }}</b></li>
        </ul>
      </div>

      <div class="actions">
        <el-button type="text" @click.stop="handleShowExeLog" size="mini">执行日志</el-button>
        <div class="btn-open" @click.stop="emptyFn" v-tippy="{ arrow: true }" content="是否生效">
          <el-switch v-model="t.status" @change="handleChangeStatus(t)"
                     :active-value="1" :inactive-value="2" active-text=""></el-switch>
        </div>
        <el-button type="text" @click.stop="handleRemove(t, idx)"><i class="el-icon-delete"></i></el-button>
      </div>
    </div>

    <div>
      <el-drawer
        :title="currentNodeTitle"
        v-model="propShow"
        :append-to-body="true"
        :direction="direction"
        class="wf-node-prop-drawer"
        size="96%"
        :before-close="handlePropClose"
      >
        <order-robot
          v-if="propShow"
          :robot="currentInfo"
          :save-mode="saveMode"
          :type="type"
          :form-id="form?.form_id"
          @close="handleClose"
          @save="handleSave"
        />
      </el-drawer>
    </div>
  </div>
</template>

<style scoped lang="scss">
.tip-txt {
  font-size: 12px;
  color: #999;
  margin: 0 10px;
}
.sync-tasks {
  font-size: 12px;
  padding: 20px;

  .sync-task {
    border: 1px solid #F1F1F1;
    border-radius: 5px;
    padding: 10px 15px;
    position: relative;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #F5FCFE;
    margin-bottom: 10px;
    cursor: pointer;

    &:hover, &.active {
      border-color: #409eff;
      background-color: #ecf5ff;

      .seq {
        background: #409eff;
        color: #FFF;
      }
    }

    .seq {
      position: absolute;
      left: 0px;
      top: 0px;
      width: 20px;
      height: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #F1F1F1;
      border-top-left-radius: 5px;
      color: #333;
      border-bottom-right-radius: 5px;
    }

    .info {
      margin-left: 10px;
      flex: 1;
      font-size: 13px;
      ul, li {
        list-style-type: none;
        margin: 0;
        padding: 0;
      }

      li {
        line-height: 1.8;
      }
    }
    .btn-open {
      margin: 0px 10px;
    }

    .actions {
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }
  }
}

p {
  line-height: 1.5;
  font-size: 12px;
  color: #999;

  &:last-child {
    margin-bottom: 0px;
    margin-top: 5px;
  }
}
</style>
